package com.mygame.xinyue;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class SpringContext implements ApplicationContextAware, InitializingBean {
    @Autowired
    public static ApplicationContext context;

    public static void init(Class clz){
//        ApplicationContext ctx = new AnnotationConfigApplicationContext(clz);
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-context.xml");
        context = ctx;
    }

    // 将容器中部分已经注入的Bean 放到某一个Map 中,重写InitializingBean
    @Override
    public void afterPropertiesSet() throws Exception {


    }
    @Override
    public void setApplicationContext(ApplicationContext  applicationContext) throws BeansException {
        SpringContext.context = applicationContext;
    }
    public static <T> List<T> getBeanListOfType(Class<T> clazz) {
        List<T> result = new ArrayList<>();
        Map<String, T> map = context.getBeansOfType(clazz);
        if (null != map) {
            result.addAll(map.values());
        }
        return result;
    }
}